﻿using S7Cat.Enums;
using System.Diagnostics;

namespace S7Cat.Models
{
    [DebuggerDisplay("{ToCode()}")]
    public readonly struct DataItemAddress(DataType dataType = DataType.DataBlock, ushort db = 1, ushort startAdr = 0, ushort byteLength = 1, byte bitAdr = 255)
    {
        public DataType DataType { get; init; } = dataType;
        public ushort DB { get; init; } = db;
        public ushort StartAdr { get; init; } = startAdr;
        public ushort ByteCount { get; init; } = byteLength;
        public byte BitAdr { get; init; } = bitAdr;

        public readonly bool IsBitValue => BitAdr <= 7;

        public readonly DataItemAddress Clone()
        {
            return new(DataType, DB, StartAdr, ByteCount, BitAdr);
        }

        internal readonly DataItemAddress Split(int start, int length)
        {
            var newAdr = (ushort)(StartAdr + start);
            var newByteCount = (ushort)length;

            return new DataItemAddress(DataType, DB, newAdr, newByteCount);
        }
        internal readonly DataItemAddress Split(Range byteRange)
        {
            var newAdr = (ushort)(StartAdr + byteRange.Start.Value);
            var newByteCount = (ushort)(byteRange.End.Value - byteRange.Start.Value);

            return new DataItemAddress(DataType, DB, newAdr, newByteCount);
        }

        public readonly string ToCode()
        {
            return IsBitValue
                ? $"{{{Enum.GetName(DataType)} DB={DB}, StartAdr={StartAdr}, Length={ByteCount}, BitAdr={BitAdr}}}\r\n"
                : $"{{{Enum.GetName(DataType)} DB={DB}, StartAdr={StartAdr}, Length={ByteCount}}}\r\n";
        }
    }
}
